<?php
namespace app\admin\controller;

use think\Controller;
use app\admin\model\User as Users;
use app\admin\model\TokenUser;

class Login extends Controller
{
    private $cModel;   //当前控制器关联模型

    public function initialize()
    {
        parent::initialize();
        $this->cModel = new Users;   //别名：避免与控制名冲突
    }
    
    public function index()
    {
        $userId = session('userId');
        if (!empty($userId)){
          //  $this->redirect(url('admin/index/index'));
        }else{
            return $this->fetch();
        }
        return $this->fetch();
    }
    
    public function checkLogin()
    {
        if(request()->isPost()){
            $data = input('post.');
//            if(!captcha_check($data['code'])){
//                return ajaxReturn(lang('code_error'));
//            };
            $where = ['username' => $data['username'] ];
            $user = $this->cModel->where($where)->find();
            if(!empty($user)){
                if($user['status'] != '1'){
                    return json(['code' => 404, 'msg' => '用户被禁用', 'data' => null]);
                }elseif($user['password'] != md5($data['password'])){
                    return json(['code' => 404, 'msg' => '密码错误', 'data' => null]);
                }else{
                    session('userId',$user['id']);
                    // 更新登陆信息
                    $ip = request()->ip();
                    //$ip = '111.10.243.171';
                    $updata = [
                        'logins' => $user['logins']+1,
                        'last_time' => time(),
                        'last_ip' => $ip,
                    ];
                    $where = ['id' => $user['id']];
                    $this->cModel->where($where)->update($updata);
                    return json(['code' => 0, 'msg' => '登录成功', 'data' => null]);
                }
            }else{
                return json(['code' => 404, 'msg' => '用户不存在', 'data' => null]);
            }
        }
    }
    
    public function loginOut($params='')
    {
        session('userId', null);
        session('user_token', null);
        cookie('name', null);
        cookie('uname', null);
        cookie('uid', null);
        cookie('avatar', null);
        $this->redirect('Login/index', $params);
    }
    
    public function restLogin(){
        return $this->fetch();
    }
}
